import os

import facade
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")
topPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(topPath, "download", "bookan_shichuan", "download", "cover")
BaseDir.create_dir(sPath)


class DownCover(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutil = facade.MysqlUtiles(configfile, "db", logger=self.logger)

    def down_cover(self, jid, url):
        filepath = BaseDir.get_new_path(sPath, jid + ".jpg")
        if BaseDir.is_file_exists(filepath):
            print("文件存在")
            return True

        BoolResult, errString, r = facade.BaseRequest(url, endstring="", timeout=30)
        if BoolResult:
            ImageFile.img_to_format_jpg(r.content, filepath)
            return True
        else:
            print("下载图片失败")
            return False

    def map_cover(self):
        provider = 'ctgubookanjournal'
        filePath = provider + '_cover.txt'
        nCount = 0
        with open(filePath, mode='w', encoding='utf-8') as f:
            for path, dirNames, fileNames in os.walk(sPath):
                for fileName in fileNames:
                    # 分离文件名与扩展名 返回文件名和扩展名
                    journal = os.path.splitext(fileName)[0]
                    line = provider + '@' + journal + '★/smartlib/' + provider + '/' + fileName + '\n'
                    f.write(line)
                    nCount += 1
        print('nCount:' + str(nCount))

    def task(self):
        sql = "select jid,cover from journal where cover_stat = 0"
        rows = self.mysqlutil.SelectFromDB(sql)
        for row in rows:
            if self.down_cover(row[0], row[1]):
                sql = "update journal set cover_stat=1 where jid='{}'".format(row[0])
                self.mysqlutil.ExeSqlToDB(sql)
            else:
                sql = "update journal set cover_failcount=cover_failcount+1 where jid='{}'".format(row[0])
                self.mysqlutil.ExeSqlToDB(sql)


def main():
    down = DownCover()
    down.task()
    down.map_cover()


if __name__ == "__main__":
    main()
